import { useEffect, useState, useCallback, useMemo } from 'react';
import { List, Checkbox, Input, Radio, Empty } from 'antd';
import service from './service';
import { PREFIX } from './utils/consts';
import { decorateKey, getMemberIconByKey, getLowercase } from './utils';
import { getMessage, TextWidget } from '@inbiz/react';
import { InbizIcon } from '@inbiz/utils';
import PageComponent from './components/PageComponent';

export default function UserGroupTab(props: any) {
  const [data, _data] = useState<any[]>([]);
  const [pagination, $pagination] = useState<any>({});
  const [searchValue, _searchValue] = useState('');

  const { selectedRowKeys, multiple, setSelected, tabKey, forbiddenItems, filterItems, configEvents, groupFilteringRules, groupsIds, collectivization } = props;

  const decorateData = decorateKey(tabKey, (data) => {
    return {
      icon: getMemberIconByKey(tabKey, forbiddenItems.includes(data.id) ? true : false),
    };
  });
  const GroupComponent = multiple ? Checkbox.Group : Radio.Group;

  const idsParam = useMemo(() => {
    if(groupsIds?.length == 0 || collectivization){
      return {}
    } else {
      if(groupFilteringRules == 'exceptSelected'){
        return {
          banGroupIds: groupsIds?.join(','),
        }
      } else {
        return {
          pickGroupIds: groupsIds?.join(','),
        }
      }
    }
  }, [groupFilteringRules, groupsIds]);

  const { getUserGroupList, searchUserGroupList } = service;

  const _getUserGroupList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onGetGroupsParams?.(params)) || params;
    const data = await (configEvents.current?.onGetGroupsRequest || getUserGroupList)(newParams as any);
    return await configEvents.current?.onGetGroupsData?.(data) || data;
  }, []);

  const _searchUserGroupList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onSearchGroupsParams?.(params)) || params;
    const data = await (configEvents.current?.onSearchGroupsRequest || searchUserGroupList)(newParams as any);
    return await configEvents.current?.onSearchGroupsData?.(data) || data;
  }, []);

  const onSearch = (index?: number, size?: number) => {
    _searchUserGroupList({
      groupName: searchValue,
      pageIndex: index ?? pagination.current,
      pageSize: size ?? pagination.pageSize,
      ...idsParam,
    })
      .then((res) => {
        const data = JSON.parse(res.rows);
        $pagination({
          total: res.total,
          pageSize: res.pageSize,
          current: res.pageIndex,
        });
        _data(
          (getLowercase(data, tabKey) || [])
            .map(decorateData)
            ?.filter((item: any) => !filterItems?.includes(item?.identityid)),
        );
      });
  };

  const onChange = (e) => {
    _searchValue(e.target.value);
  };

  useEffect(() => {
    _getUserGroupList({
      pageIndex: 1,
      pageSize: 10,
      ...idsParam,
    })
      .then((res) => {
        $pagination({
          total: res.total,
          pageSize: res.pageSize,
          current: res.pageIndex,
        });
        const data = JSON.parse(res.rows);
        _data(
          (getLowercase(data, tabKey) || [])
            .map(decorateData)
            ?.filter((item: any) => !filterItems?.includes(item?.identityid)),
        );
      });
  }, []);

  return (
    <div className={`${PREFIX}-tab`}>
      <div className={`${PREFIX}-uniqueSearchBar`}>
        <Input
          // 输入用户组名称
          placeholder={getMessage(`MemberSelect.lang.enterUserGourpName`)}
          style={{ width: 260 }}
          value={searchValue}
          onChange={onChange}
          suffix={
            <InbizIcon
              type="icon-ic-sousuo"
              style={{ fontSize: '15px', color: '#d9d9d9' }}
              onClick={() => onSearch()}
            />
          }
          onPressEnter={() => {
            onSearch();
          }}
        />
      </div>
      <GroupComponent
        value={multiple ? selectedRowKeys : selectedRowKeys?.[0]}
        style={{
          display: 'block',
          borderTop: '1px solid #ddd',
          height: 'calc(100% - 86px)',
        }}
      >
        <List
          className={`${PREFIX}-dataList`}
          style={{
            height: '100%',
          }}
          locale={{
            emptyText: (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={<TextWidget>MemberSelect.lang.noData</TextWidget>}
              />
            ),
          }}
          itemLayout="vertical"
          dataSource={data}
          rowKey={(row) => row.key}
          bordered={false}
          split={false}
          pagination={false}
          renderItem={(item, index) => {
            let _disabled = forbiddenItems.includes(item.id);
            return (
              <List.Item
                onClick={(e) => {
                  if (_disabled) {
                    return;
                  }
                  let keys = [...selectedRowKeys];
                  let index = keys.indexOf(item.key);
                  if (!multiple) {
                    keys = [item.key];
                  } else {
                    if (index > -1) {
                      keys.splice(index, 1);
                    } else {
                      keys.push(item.key);
                    }
                  }
                  setSelected(keys, data);
                  props.onRowClick?.(item, index);
                }}
                style={{ cursor: _disabled ? 'not-allowed' : 'pointer' }}
                className={selectedRowKeys.includes(item?.key) ? 'memberItemSelected' : ''}
              >
                <List.Item.Meta
                  avatar={
                    <span style={{ cursor: _disabled ? 'not-allowed' : 'pointer' }}>
                      {multiple ? (
                        <Checkbox
                          value={item.key}
                          style={{ pointerEvents: 'none' }}
                          disabled={_disabled}
                        >
                          {item.icon}
                        </Checkbox>
                      ) : (
                        <Radio value={item.key} style={{ pointerEvents: 'none' }}>
                          {item.icon}
                        </Radio>
                      )}
                    </span>
                  }
                  title={
                    _disabled ? (
                      <div style={{ color: 'rgba(0, 0, 0, 0.45)' }}>{item.name}</div>
                    ) : (
                      item.name
                    )
                  }
                ></List.Item.Meta>
              </List.Item>
            );
          }}
        />
      </GroupComponent>
      <PageComponent
        options={[10, 20, 30, 40, 50]}
        className={`${PREFIX}-dataList-pagination`}
        total={pagination.total || 0}
        current={pagination.current || 1}
        pageSize={pagination.pageSize || 0}
        onChange={(current, pageSize) => {
          $pagination({
            ...pagination,
            current: current,
            pageSize: pageSize,
          });
          onSearch(current, pageSize);
        }}
      />
    </div>
  );
}
